/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.context;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.function.Supplier;

/**
 * @author Dillon
 * @date 2024/7/10
 * @slogan 致敬大师 致敬未来的你
 * @desc 缓存持久化过滤器 用户将缓存持久化到其他地方 磁盘 内存等
 */
public class SecurityContextHolderFilter extends GenericFilterBean {

	/**
	 * 过滤器链已执行标记
	 */
	private static final String FILTER_APPLIED = SecurityContextHolderFilter.class.getName() + ".APPLIED";

	/**
	 * 持久化实现类
	 */
	private final SecurityContextRepository securityContextRepository;

	/**
	 * 内存策略类 默认 threadLocal
	 */
	private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();

	/**
	 * 构造函数
	 *
	 * @param securityContextRepository 持久化实现类
	 */
	public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) {
		Assert.notNull(securityContextRepository, "持久化实现类不能为空");
		this.securityContextRepository = securityContextRepository;
	}

	/**
	 * 核心 过滤方法
	 *
	 * @param request  请求对象
	 * @param response 响应对象
	 * @param chain    过滤器链
	 * @throws IOException      执行异常
	 * @throws ServletException 执行异常
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
	}

	/**
	 * 核心 过滤方法
	 * 这里相比较原始过滤器类少了设置到持久化内存中，所有登录成功设置自己实现
	 * 主要是为了提高性能
	 *
	 * @param request  请求对象
	 * @param response 响应对象
	 * @param chain    过滤器链
	 * @throws IOException      执行异常
	 * @throws ServletException 执行异常
	 */
	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		// 确保一次请求，该过滤器执行一次
		if (request.getAttribute(FILTER_APPLIED) != null) {
			chain.doFilter(request, response);
			return;
		}
		// 执行标记设置
		request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
		// 从持久化类中获取上下文提供者
		Supplier<SecurityContext> deferredContext = this.securityContextRepository.loadDeferredContext(request);
		try {
			// 设置到内存中
			this.securityContextHolderStrategy.setDeferredContext(deferredContext);
			chain.doFilter(request, response);
		} finally {
			// 最后执行内存清除
			this.securityContextHolderStrategy.clearContext();
			request.removeAttribute(FILTER_APPLIED);
		}
	}

	/**
	 * 设置自定义的缓存实现策略类
	 *
	 * @param securityContextHolderStrategy 缓存实现策略类
	 */
	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
		Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
		this.securityContextHolderStrategy = securityContextHolderStrategy;
	}

}
